package gov.pbc.nn.kjgl.maintenance.job;

import gov.pbc.nn.core.dao.CommonHibernateDao;
import gov.pbc.nn.kjgl.maintenance.entity.SysPwd;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import javax.annotation.Resource;

import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.type.StringType;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.bstek.bdf2.core.model.Message;
import com.bstek.bdf2.core.orm.hibernate.ISessionCallback;

/**
 * 根据系统档案中定义的密码变更周期定期提醒系统管理员A角更新密码
 * 
 * @author Administrator
 * 
 */
@Component(NotifyChangePwdJob.BEAN_ID)
public class NotifyChangePwdJob implements Job {
	public static final String BEAN_ID = "gov.pbc.nn.kjgl.maintenance.job.NotifyChangePwdJob";

	@Resource(name = CommonHibernateDao.BEAN_ID)
	private CommonHibernateDao hibernateDao;

	private final static int DAY = -3;
	private final static String SENDER = "系统自动";

	@Override
	@Transactional
	public void execute(JobExecutionContext context) throws JobExecutionException {
		final String sql = "SELECT\n" + "	p.*, s.USERNAME_\n" + "FROM\n" + "	t_sys_pwd P\n"
				+ "INNER JOIN t_sys_operation_staff S ON P.SYS_ID_ = S.SYS_ID_\n" + "AND s.AB_ = 'A'\n" + "WHERE\n"
				+ "	DATE_FORMAT(\n" + "		DATE_ADD(\n" + "			p.MODIFY_DATE_,\n"
				+ "			INTERVAL p.CLCLE_ DAY\n" + "		),\n" + "		'%Y-%m-%d'\n"
				+ "	) = DATE_ADD(CURDATE(), INTERVAL :day DAY)";
		this.hibernateDao.doInHibernateSession(new ISessionCallback<Void>() {

			@Override
			public Void doInSession(Session session) {
				SQLQuery query = session.createSQLQuery(sql);
				query.addEntity("p", SysPwd.class);
				query.addScalar("s", StringType.INSTANCE);
				query.setInteger("day", DAY);
				List<Object[]> list = query.list();

				if (list != null && list.size() > 0) {
					for (Object[] array : list) {
						SysPwd pwd = (SysPwd) array[0];
						String toUser = (String) array[1];

						Message msg = new Message();
						msg.setId(UUID.randomUUID().toString());
						msg.setSendDate(new Date());
						msg.setSender(SENDER);
						msg.setReply(false);
						msg.setRead(false);
						msg.setTitle("密码即将过期，请尽快更新密码！");
						if (pwd.getType() == 1) {
							msg.setContent(
									"【" + pwd.getSysName() + "】管理员【" + pwd.getUser() + "】密码将在" + DAY + "天后过期，请尽快更新密码！");
						} else {
							msg.setContent("【" + pwd.getSysName() + "】服务器【" + pwd.getServer() + "】密码将在" + DAY
									+ "天后过期，请尽快更新密码！");
						}
						msg.setReceiver(toUser);
						session.save(msg);
					}
				}
				return null;
			}

		});

	}

}
